package com.kin207.netty.message.http.listener;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.net.httpserver.HttpServer;
import com.kin207.netty.listener.Listener;
import com.kin207.netty.listener.ListenerConfig;
import com.kin207.netty.message.http.handler.HttpMessageHttpHandle;
import com.kin207.netty.server.IServer;
import com.kin207.netty.util.StringParseUtils;

public class HttpMessageListener implements Listener<IServer>{
	final static Logger logger = LoggerFactory.getLogger(HttpMessageListener.class);
	
	private HttpServer httpServer;
	
	private int port = 9000;
	private String contextPath = "/msg";
	private int maxThreads = 200;
	
	private IServer server;
	
	public void initialize(ListenerConfig cfg) {
		if(cfg==null){
			return;
		}
		StringParseUtils spu = new StringParseUtils();
		if(!spu.set(cfg.getParam("port")).isEmpty()){
			port = spu.getInt();
		}
		
		if(!spu.set(cfg.getParam("contextPath")).isEmpty()){
			contextPath = spu.get();
		}
		
		if(!spu.set(cfg.getParam("maxThreads")).isEmpty()){
			maxThreads = spu.getInt();
		}
	}

	public synchronized void created(IServer t) {
		if(httpServer!=null){
			logger.info("http server is run");
			return ;
		}
		server = t;
		logger.info("init http server, port:{}, contextPath:{}, maxThreads:{}", port, contextPath, maxThreads);
		 InetSocketAddress addr = new InetSocketAddress(port); 
		try {
			httpServer = HttpServer.create(addr, maxThreads);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
		
		httpServer.createContext(contextPath, new HttpMessageHttpHandle(server));
		//httpServer.setExecutor(arg0);
		
		httpServer.start();
		logger.info("http server success.");
	}

	public void destroyed(IServer t) {
		if(httpServer!=null){
			logger.info("http server close.");
			httpServer.stop(0);
		}
		server = null;
	}

	public HttpServer getHttpServer() {
		return httpServer;
	}

	public void setHttpServer(HttpServer httpServer) {
		this.httpServer = httpServer;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getContextPath() {
		return contextPath;
	}

	public void setContextPath(String contextPath) {
		this.contextPath = contextPath;
	}

	public int getMaxThreads() {
		return maxThreads;
	}

	public void setMaxThreads(int maxThreads) {
		this.maxThreads = maxThreads;
	}

	public IServer getServer() {
		return server;
	}

	public void setServer(IServer server) {
		this.server = server;
	}
	
	
}
